package com.jackrain.nea.wms.service;


import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.jackrain.nea.config.Resources;
import com.jackrain.nea.exception.NDSException;
import com.jackrain.nea.sys.CommandAdapter;
import com.jackrain.nea.util.ValueHolder;
import com.jackrain.nea.wms.api.BaseWmsSaveCmd;
import com.jackrain.nea.wms.mapper.WmsSqlMapper;
import com.jackrain.nea.wms.utils.WmsQueryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;


@Slf4j
@Component
@Service(protocol = "dubbo", validation = "true", version = "1.0", group = "wms")
public class BaseWmsSaveCmdImpl extends CommandAdapter implements BaseWmsSaveCmd {

    @Autowired
    private WmsQueryService wmsQueryService;

    @Autowired
    private WmsSqlMapper wmsSqlMapper;

    @Override
    @Transactional
    public ValueHolder execute(HashMap map) throws NDSException {

        ValueHolder vh = new ValueHolder();

        JSONObject param = JSON.parseObject(JSON.toJSONStringWithDateFormat(map.get("param"), "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteMapNullValue), Feature.OrderedField);
        if (null == param || param.size() == 0 || param.getJSONArray("data").size() <= 0) {
            log.error("BaseWmsSaveCmdImpl-->param-->{}" ,param);
            throw new NDSException("参数格式错误！");
        }
        log.info("BaseWmsSaveCmdImpl--param-->{}", param);
        StringBuffer message = new StringBuffer("该数据已存在中间表中!->>");
        JSONArray jsonArray = param.getJSONArray("data");
        if (param.containsKey("maintablename")) {
            //主子表新增
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject fixcolum = jsonArray.getJSONObject(i);
                JSONObject mainJo = fixcolum.getJSONObject("mainData");

                //查询单据是否已存在
                String billno = mainJo.getString("bill_no");
                String tablename = param.getString("maintablename");
                int count = 0;
                if ("wms_t_in_notices".equals(tablename)) {
                    count = wmsSqlMapper.selectInBillNoNumber(billno);
                } else if ("wms_t_out_notices".equals(tablename)) {
                    count = wmsSqlMapper.selectOutBillNoNumber(billno);
                }
                if (count > 0) {
                    message.append(billno+",");
                    continue;
                }

                if (mainJo.containsKey("bill_date")) {
                    mainJo.put("bill_date", stringToCustomerDate(mainJo.getString("bill_date")));
                }
                if (mainJo.containsKey("date_in")) {
                    mainJo.put("date_in", stringToCustomerDate(mainJo.getString("date_in")));
                }
                if (mainJo.containsKey("write_time")) {
                    mainJo.put("write_time", minToCustomerDate(mainJo.getLong("write_time")));
                }
                if (mainJo.containsKey("recive_time")) {
                    mainJo.put("recive_time", minToCustomerDate(mainJo.getLong("recive_time")));
                }
                if (mainJo.containsKey("creation_date")) {
                    mainJo.put("creation_date", minToCustomerDate(mainJo.getLong("creation_date")));
                }
                if (mainJo.containsKey("modified_date")) {
                    mainJo.put("modified_date", minToCustomerDate(mainJo.getLong("modified_date")));
                }
                if (mainJo.containsKey("recive_status")) {
                    mainJo.put("recive_status", Integer.parseInt(mainJo.getString("recive_status")));
                }
                //新增主表
                HashMap sTableMap = new HashMap();
                sTableMap.put("tableName", param.getString("maintablename"));
                sTableMap.put("insertKeys", mainJo);
                Long objid = wmsQueryService.commandInsert(sTableMap);
                //新增子表
                JSONArray childArray = fixcolum.getJSONArray("itemData");
                for (int a = 0; a < childArray.size(); a++) {
                    JSONObject childJo = childArray.getJSONObject(a);
                    childJo.put("bill_id", objid);
                    if (childJo.containsKey("recive_time")) {
                        childJo.put("recive_time", minToCustomerDate(childJo.getLong("recive_time")));
                    }
                    if (childJo.containsKey("creation_date")) {
                        childJo.put("creation_date", minToCustomerDate(childJo.getLong("creation_date")));
                    }
                    if (childJo.containsKey("modified_date")) {
                        childJo.put("modified_date", minToCustomerDate(childJo.getLong("modified_date")));
                    }
                    HashMap cTableMap = new HashMap();
                    cTableMap.put("tableName", param.getString("childtablename"));
                    cTableMap.put("insertKeys", childJo);
                    wmsQueryService.commandInsert(cTableMap);
                }
            }
        } else {
            //单表新增
            String tablename = param.getString("tablename");
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = new JSONObject();
                jsonObject = jsonArray.getJSONObject(i);
                if (jsonObject.containsKey("modified_date")) {
                    jsonObject.put("modified_date", stringToDate(jsonObject.getString("modified_date")));
                }
                if (jsonObject.containsKey("write_time")) {
                    jsonObject.put("write_time", stringToDate(jsonObject.getString("write_time")));
                }
                HashMap sTableMap = new HashMap();
                sTableMap.put("tableName", tablename);
                sTableMap.put("insertKeys", jsonObject);
                wmsQueryService.commandInsert(sTableMap);
            }
        }
        message.deleteCharAt(message.length()-1);
        vh.put("data", jsonArray);
        vh.put("code", 0);
        vh.put("message", Resources.getMessage("新增成功;")+message);
        return vh;
    }

    /**
     * str TO Date
     *
     * @param str
     * @return Date
     */
    public Date stringToDate(String str) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//小写的mm表示的是分钟
        Date mdate = null;
        try {
            mdate = sdf.parse(str);
        } catch (Exception e) {
            throw new NDSException(e.getMessage());
        }
        return mdate;
    }

    /**
     * str TO Date
     *
     * @param str
     * @return Date
     */
    public Date stringToCustomerDate(String str) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");//小写的mm表示的是分钟
        Date mdate = null;
        try {
            mdate = sdf.parse(str);
        } catch (Exception e) {
            throw new NDSException(e.getMessage());
        }
        return mdate;
    }

    /**
     * str TO Date
     *
     * @param millionSeconds
     * @return Date
     */
    public Date minToCustomerDate(Long millionSeconds) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(millionSeconds);
        Date date = c.getTime();
        try {
            date = sdf.parse(sdf.format(date));
        } catch (Exception e) {
            throw new NDSException(e.getMessage());
        }
        return date;
    }
}